package com.zhongge.util;
import java.sql.*;
import java.util.ResourceBundle;

/**
 * @ClassName DBUtils
 * @Description TODO 数据库操作对象
 * @Author zhongge
 * @Version 1.0
 */
public class DBUtils {
    //工具类一般都是私有构造
    private DBUtils() {

    }

    //读取配置文件
    /*
    public static final ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
    由于jdbc.properties写在resources中如果 想要让他参与编译到根路径下
    必须右键==》mark directory as ==> resources root
    否则程序运行的时候由于没有参与编译所以找不到该文件
     */
    //ResourceBundle 资源包
    public static final ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
    public static final String DRIVER = bundle.getString("driver");
    public static final String URL = bundle.getString("url");
    public static final String USERNAME = bundle.getString("username");
    public static final String PASSWORD = bundle.getString("password");

    //注册驱动
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //创建连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    //获取手动提交
    public static Connection getConnectionHandCommit() throws SQLException {
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        //这一步在修改数据==》比如插入时候需要手动 connection.commit();提交才会将数据插入到数据库
        connection.setAutoCommit(false);//false代表无需自动提交，需要手动提交
        return connection;
    }
    //释放资源
    public static void close(Connection connection, Statement statement,
                      ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
